package 数据结构说难也不难.数组;

public class 寻找数组中心下标 {

    public static int pivotIndex(int[] nums){
        int left = 0;
        int right = nums.length - 1;

        if (right <= 1){
            return -1;
        }

        int leftSum = 0;
        int rightSum = nums[right];



        while (left <= right){

            if (leftSum == rightSum && right - left == 1){
                return left;
            }else{
                //if (Math.abs(leftSum) < Math.abs(rightSum)){
                if (leftSum < rightSum){
                    left++;
                    if (left > nums.length  -1){
                        return -1;
                    }
                    int leftValue = left == 0 ? 0: nums[left -1];
                    leftSum = leftSum + leftValue;
                }else {
                    right--;
                    if (right < 0){
                        return -1;
                    }
                    rightSum = rightSum + nums[right];
                }
            }

        }
        return  -1;
    }

    public static int pivotIndex2(int[] nums){
        int right = nums.length - 1;

        if (right <= 1){
            return -1;
        }

        int total = 0;
        for (int i = 0; i < nums.length; i++) {
            total = total + nums[i];
        }
        int leftSum = 0;
        for (int i = 0; i < nums.length; i++) {
            //
            if (total - nums[i] -leftSum == leftSum){
                return i;
            }
            leftSum = leftSum + nums[i];
        }
        return -1;
    }



    public static void main(String[] args) {

        int[] nums = {1,7,3,6,5,6};
        //int[] nums = {2,1,-1};

        System.out.println(pivotIndex2(nums));

    }
}
